<script setup>
// 组件对外暴露一个方法 open,  基于 open 的参数，初始化表单数据，并判断区分是添加 还是 编辑
// 1. open({ })                   =>  添加操作，添加表单初始化无数据
// 2. open({ id: xx,  ...  })  =>  编辑操作，编辑表单初始化需回显
import { ref } from 'vue'
import { artAddChannelService, artEditChannelService, artDelChannelService } from '@/api/article'
import { ElMessage } from 'element-plus'
// 表单
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
// 分类名必须是1-10位的非空字符
// 分类别名必须是1-15位的字母数字
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
}
const dialogVisible = ref(false)
const open = (row) => {
  // console.log(row)
  dialogVisible.value = true
  formModel.value = { ...row }
  console.log(formModel.value)
}
// 提交表单
const formRef = ref()
const emit = defineEmits(['success'])
const onSubmit = async () => {
  // 校验
  await formRef.value.validate()
  !formModel.value.id ?
    await artAddChannelService(formModel.value) :
    await artEditChannelService(formModel.value)
  ElMessage({
    type: 'success',
    message: formModel.value.id ? '编辑成功' : '添加成功'
  })
  dialogVisible.value = false
  // 数据回显
  emit('success')
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="formModel.id ? '编辑分类' : '添加分类'" width="30%">
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px" style="padding-right: 30px;">
      <el-form-item label="分类名字" prop="cate_name">
        <el-input minlength="1" maxlength="10" v-model="formModel.cate_name" placeholder="请输入分类名字"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input minlength="1" maxlength="15" v-model="formModel.cate_alias" placeholder="请输入分类别名"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="onSubmit" type="primary">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
